package com.ja.openchat.ui.me;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.views.SimpleTextWatcher;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LogoutDeviceActivity extends JaBaseActivity {

    @BindView(R.id.old_phone_number)
    TextView old_phone_number;
    @BindView(R.id.editCodeText)
    EditText editCodeText;
    @BindView(R.id.tv_code)
    TextView tv_code;
    @BindView(R.id.logoutBtn)
    View logoutBtn;
    @BindView(R.id.codeEditLayout)
    View codeEditLayout;
    @BindView(R.id.editPasswordText)
    EditText editPasswordText;
    @BindView(R.id.logoutTitle)
    TextView logoutTitle;
    @BindView(R.id.logoutIntro)
    TextView logoutIntro;

    private boolean logoutByPhone = true;
    @Override
    public void initData() {
        setTitle(getString(R.string.logout_session));
        UserInfo user = UserInfo.getUserInfo();
        if(user!=null){
            if(!TextUtils.isEmpty(user.phone_number)){
                codeEditLayout.setVisibility(View.VISIBLE);
                editPasswordText.setVisibility(View.GONE);
                old_phone_number.setText(Common.formatPhoneNumber(user.phone_number));
            }else{
                logoutByPhone = false;
                codeEditLayout.setVisibility(View.GONE);
                editPasswordText.setVisibility(View.VISIBLE);
                old_phone_number.setText(user.username);
            }
        }else{
            old_phone_number.setText("");
        }
        if(logoutByPhone){
            logoutIntro.setText(getString(R.string.by_code_verify_account));
            logoutTitle.setText(getString(R.string.verify_account));
            editCodeText.addTextChangedListener(new SimpleTextWatcher(){
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    logoutBtn.setEnabled(!TextUtils.isEmpty(editCodeText.getText()));
                }
            });
        }else{
            logoutIntro.setText(getString(R.string.by_password_verify_account));
            logoutTitle.setText(getString(R.string.verify_account));
            editPasswordText.addTextChangedListener(new SimpleTextWatcher(){
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    logoutBtn.setEnabled(!TextUtils.isEmpty(editPasswordText.getText()));
                }
            });
        }
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    private Disposable disposable;
    private void countDown(){
        tv_code.setEnabled(false);
        disposable = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> {
                    int time = (int) (59 - aLong);
                    if (time > 0) {
                        tv_code.setText(time + getString(R.string.second_text));
                    } else {
                        tv_code.setText(getString(R.string.verify_code));
                    }
                })
                .doOnComplete(() -> {
                    tv_code.setEnabled(true);
                    tv_code.setText(getString(R.string.verify_code));
                })
                .subscribe();
    }

    private void getPhoneCode(){
        showProgress();
        TelegramManager.getTelegramManager().gotSmsCode(this, TelegramManager.SmsCodeType.SmsCodeType_DeleteAccount, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if(obj==null||!obj.ok){
                    showErrorTip(getString(R.string.request_error));
                }else{
                    countDown();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    @OnClick({R.id.tv_code,R.id.logoutBtn})
    void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_code:
                getPhoneCode();
                break;
            case R.id.logoutBtn:
                deleteAccount();
                break;
        }
    }
    private void deleteAccount(){
        showProgress();
        if(logoutByPhone){
            TelegramManager.getTelegramManager().verifySmsCode(this, TelegramManager.SmsCodeType.SmsCodeType_DeleteAccount, editCodeText.getText().toString(), new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    if(obj!=null&&obj.ok){
                        logoutOtherDevices();
                    }else{
                        hideProgress();
                        showErrorTip(getString(R.string.request_error));
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }else{
            TelegramManager.getTelegramManager().verifyPassword(this, editPasswordText.getText().toString(), new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    if(obj!=null&&obj.ok){
                        logoutOtherDevices();
                    }else{
                        hideProgress();
                        showErrorTip(getString(R.string.wrong_password_re_enter));
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }

    }


    private void logoutOtherDevices(){
        TelegramManager.getTelegramManager().terminateAllOtherSessions(this, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                realDeleteAccount();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                realDeleteAccount();
            }
        });
    }


    private void realDeleteAccount(){
        TelegramManager.getTelegramManager().deleteAccount(LogoutDeviceActivity.this, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if(obj!=null&&obj.ok){
                    showErrorTip(getString(R.string.logout_account_success));
                    App.getInstanse().toLoginView();
                }else{
                    showErrorTip(getString(R.string.request_error));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_logout_device;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(disposable!=null&&!disposable.isDisposed()){
            disposable.dispose();
        }
    }
}
